<?php
declare (strict_types = 1);
namespace app\adminapi\logic\system\auth;
use adminmatrix\server\app\logic\BaseLogic;
use adminmatrix\annotation\Inject;
use app\adminapi\model\system\auth\AdminUser;
use app\adminapi\model\system\auth\AdminUser as AdminUserModel;
use app\adminapi\model\system\auth\Role;
use app\adminapi\validate\system\auth\AdminUserValidate;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\HttpException;
use think\Request;
use think\facade\Db;
class AdminUserLogic extends BaseLogic
{
    #[Inject]
    protected AdminUserModel $model;



    public function save(Request $request) : bool
    {
        $salt = uniqid('matrix_');
        $params = $request->post();
        if (isset($params['password']))
        {
            $params['password'] = md5( md5($params['password'] . $salt) );
            $params['salt']     =   $salt;
        }

        $save[] = $this->model->save($params);

        $save[] = $this->model->info()->save($request->only(['department_id' ,'organization_id','position_id']));

        if ( $save )
        {
            return true;
        }

        return false;
    }

    public function update( Request $request) : bool
    {
        Db::startTrans();
        try {
            $params = $request->put();
            $model = $this->model->findOrEmpty($params['id']);
            if ($model->isEmpty()) throw new HttpException(200 , '管理员不存在');
            $model->role()->where('user_id' , $params['id'])-> delete();
            $role = [];
            foreach ($params['role'] as $roleId)
            {
                $role[] = [
                    'role_id' => $roleId,
                    'user_id'   =>  $params['id']
                ];
            }

            if ($model->info)
            {
                $model->info()->update($request->only(['department_id' ,'organization_id','position_id']));
            }else{
                $model->info()->save($request->only(['department_id' ,'organization_id','position_id']));

            }



            $this->model->role()->saveAll($role);

            $salt = uniqid('matrix_');

            if (isset($params['password']) && !empty($params['password']))
            {
                $params['password'] = md5($params['password'] . $salt);
                $params['salt']     =   $salt;
            }else{
                unset($params['password']);
            }
            $model->update($params);
            Db::commit();
            return true;
        } catch (HttpException $exception)
        {
            Db::rollback();
            return throw new HttpException($exception->getCode() , $exception->getMessage());
        }

    }

    public static function getRole() : array
    {
        try {
            $role = (new Role)->select();
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return throw new HttpException($e->getCode() , $e->getMessage());
        }
        return $role->toArray();
    }

    public function detail() : array
    {
        $admin = AdminUser::field([
            'id','username' , 'avatar' , 'status' , 'root' , 'multipoint_login' , 'avatar' , 'nickname'
        ])->findOrEmpty($this->request->adminId);

       $result['userInfo'] = $admin;
       $result['routes'] = (new PermissionLogic($this->app)) -> getMenuByAdminId($admin->id);
        $result['permission'] = (new RoleLogic($this->app)) -> getBtnAuthByRoleId($admin);
      return $result;
    }
}